import { useState, useCallback, useEffect } from 'react';
import { GlobalRegistry } from '@inbiz/core';
import { useApp } from '@inbiz/render';
import getComponents, {
  IClassCompent,
} from './materials/getComponents';
import { TreeNode } from '@inbiz/core'
type IGroups =
  | IClassCompent
  | (IClassCompent & {
    displayName: string;
    url: string;
    outId: string;
    pattern: 0 | 1;
    data?: IClassCompent['data'];
  });

let componentsPublic = {
  groups: [] as IClassCompent[],
  data: undefined as Record<string, any> | undefined,
}
let isCustomized = false // 定制组件包是否已经加载过

// 记录定制插件的原始名称
export const customizedData: Record<string, { key: string, icon: string, title: string }> = {};

export function useComponets() {
  const [components, $components] = useState(componentsPublic);
  useEffect(() => {
    if (!components.data) {
      getComponents('web').then((res) => {
        getCustomizedData(res.component)
        $components(com => {
          return {
            groups: [...com.groups, ...res.classCompent],
            data: { ...(com.data || {}), ...res.component },
          }
        });

      });
    }
  }, []);

  useEffect(() => {
    componentsPublic = components
  }, [components]);
  return [components] as const;
}

function getCustomizedData(data: { [s: string]: unknown; } | ArrayLike<unknown>) {
  Object.values(data).forEach(item => {
    //@ts-ignore
    const key = item?.Resource?.[0].elements[0].props['x-component'] as string;
    customizedData[key] = {
      key,
      //@ts-ignore
      icon: item?.Resource?.[0].icon as string,
      //@ts-ignore
      title: item?.Behavior?.[0]?.designerLocales['zh-CN']?.title as string
    }
  })
}
